package com.study.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.study.context.BaseContext;
import com.study.dto.ActivityCollectionListPageQueryDTO;
import com.study.dto.ActivitySearchDTO;
import com.study.entity.Activity;
import com.study.entity.ActivityCollection;
import com.study.entity.ImgResource;
import com.study.mapper.ActivityMapper;
import com.study.mapper.ImgResourceMapper;
import com.study.result.PageResult;
import com.study.service.ActivityService;
import com.study.vo.ActivityDetailVO;
import com.study.vo.ActivityVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    ActivityMapper activityMapper;
    @Autowired
    ImgResourceMapper imgResourceMapper;

    /**
     * 根据状态数组获取活动列表
     *
     * @return
     */
    @Override
    public List<ActivityVO> getActivityList(ActivitySearchDTO activitySearchDTO) {
        List<ActivityVO> activityList = activityMapper.getList(activitySearchDTO);

        activityList.forEach(activityVO -> {
            //获取活动id
            Long activityId = activityVO.getId();
            //根据活动id获取活动图片
            ImgResource imgResourceList = imgResourceMapper.getActivityImageById(activityId);
            activityVO.setActivityImagePath(imgResourceList);
        });

        return activityList;
    }

    /**
     * 获取用户收藏的活动列表
     *
     * @param activityCollectionListPageQueryDTO
     * @return
     */
    @Override
    public PageResult getCollectionActivityListByUserId(ActivityCollectionListPageQueryDTO activityCollectionListPageQueryDTO) {
        // 设置分页
        PageHelper.startPage(activityCollectionListPageQueryDTO.getPage(), activityCollectionListPageQueryDTO.getPageSize());

        //获取当前线程用户id
        Long currentId = BaseContext.getCurrentId();
        if (!currentId.equals(activityCollectionListPageQueryDTO.getUserId())) {
            throw new IllegalArgumentException("非法用户id，获取失败");
        }
        //List<ActivityVO> activityList = activityMapper.getCollectionActivityListByUserId(activityCollectionListPageQueryDTO);

        Page<ActivityVO> page = activityMapper.getCollectionActivityListByUserId(activityCollectionListPageQueryDTO);

        List<ActivityVO> activityList = page.getResult();

        activityList.forEach(activityVO -> {
            //获取活动id
            Long activityId = activityVO.getId();
            //根据活动id获取活动图片
            ImgResource imgResourceList = imgResourceMapper.getActivityImageById(activityId);
            activityVO.setActivityImagePath(imgResourceList);
        });

        return new PageResult(page.getTotal(), activityList);
    }

    /**
     * 收藏活动
     *
     * @param activityId
     */
    @Override
    public void collectionActivity(Long activityId) {
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        //查询活动是否存在
        Activity activity =  activityMapper.getActivityById(activityId);
        //不存在抛出异常
        if (activity == null) {
            throw new RuntimeException("添加收藏失败，活动不存在");
        }
        //查询用户是否已经收藏
        ActivityCollection activityCollection = activityMapper.getActivityByUserIdAndActivityId(userId, activityId);
        //已经收藏抛出异常
        if (activityCollection != null) {
            throw new RuntimeException("添加收藏失败，该活动已收藏");
        }
        //计算添加时间
        LocalDateTime creatTime = LocalDateTime.now();
        //添加收藏
        activityMapper.collectionActivity(userId, activityId, creatTime);
    }

    /**
     * 取消收藏活动
     *
     * @param activityId
     */
    @Override
    public void cancelCollectionActivity(Long activityId) {
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        //查询活动是否存在
        Activity activity =  activityMapper.getActivityById(activityId);
        //不存在抛出异常
        if (activity == null) {
            throw new RuntimeException("取消收藏失败，活动不存在");
        }

        //查询用户是否已经收藏
        ActivityCollection activityCollection = activityMapper.getActivityByUserIdAndActivityId(userId, activityId);
        //已经收藏抛出异常
        if (activityCollection == null) {
            throw new RuntimeException("取消收藏失败，该活动未收藏");
        }
        //取消收藏
        Long collectionId = activityCollection.getId();
        activityMapper.cancelCollectionActivity(collectionId);
    }

    /**
     * 据活动id获取活动详情
     *
     * @param activityId
     * @return
     */
    @Override
    public ActivityDetailVO getActivityById(Long activityId) {
        // 验证活动ID的合法性（这里简单地检查是否为null或空，实际应用中可能需要更复杂的验证规则）
        if (activityId == null) {
            log.error("活动详情获取失败，活动ID不能为空");
            throw new IllegalArgumentException("活动详情获取失败");
        }

        ActivityDetailVO activityDetailVO = new ActivityDetailVO();
        //查询活动详细内容
        Activity activity = activityMapper.getActivityById(activityId);
        if (activity == null) {
            log.error("活动详情获取失败，活动不存在");
            throw new IllegalArgumentException("活动详情获取失败");
        }
        //复制属性
        BeanUtils.copyProperties(activity, activityDetailVO);

        Map map = new HashMap();
        map.put("activityId", activityId);
        map.put("openType", "activity_banner");

        //获取活动轮播图片
        List<ImgResource> activityImageList = imgResourceMapper.getActivityImageListByMap(map);
        //设置活动轮播图片列表
        activityDetailVO.setActivityImagePath(activityImageList);

        map.put("openType", "activity_detail");
        //获取活动详情图片
        List<ImgResource> activityDetailImageList = imgResourceMapper.getActivityImageListByMap(map);
        //设置活动详情图片列表
        activityDetailVO.setActivityDetailImage(activityDetailImageList);

        return activityDetailVO;
    }

    /**
     * 根据用户id和活动id判断用户是否收藏了该活动
     *
     * @param userId
     * @param activityId
     * @return
     */
    @Override
    public Boolean isCollectionByUserId(Long userId, Long activityId) {
        if (userId == null || activityId == null) {
            log.error("判断用户是否收藏活动失败，用户ID或活动ID不能为空");
            throw new IllegalArgumentException("判断用户是否收藏活动失败");
        }
        if (activityMapper.getActivityByUserIdAndActivityId(userId, activityId) != null) {
            return true;
        }
        return false;
    }
}
